<?php
/**
 * CK框架  MYSQL语句分析类
 * @author wujibing<283109896@qq.com>
 * @version   3.0
 * @category   CkFrameWork
 * @package  CkFrameWork
 * @subpackage db
 */
class mysql_Resolve
{
	/**
	 * Mysql插入语句分析
	 * @param module $obj
	 */
	public static function insert(module $obj)
	{
		$queryArr = $obj->getQueryArr();
		$insert = isset($queryArr['isReplace']) && $queryArr['isReplace'] ? 'replace':'insert';
		return $insert." into  `{$queryArr['tableName']}` (`".implode('`,`', array_keys($queryArr['data']))."`) VALUES ('".implode("','", $queryArr['data'])."')";
	}
	/**
	 * mysql更新语句
	 * @param unknown_type $option
	 */
	public static function update(module $obj)
	{
		$queryArr = $obj->getQueryArr();
		$sql = '';
		foreach($queryArr['data'] as $k=>$v)
		{
			if(isset($queryArr['math'][$k]))
			{
				$v = '`'.$k.'`'.$queryArr['math'][$k].$v;
			} else
			{
				$v = '\''.$v.'\'';
			}
			$sql .= ", `$k`={$v}";
		}
		$sql = substr($sql, 1);
		
		$sql = 'UPDATE `'.$queryArr['tableName'].'` SET '.$sql;
		$where = self::resolveWhere($queryArr['tableName'],$queryArr['where']);
		if($where)
		{
			$sql .= ' WHERE '.$where;
		}
		return $sql;
	}
	public static function delete(module $obj)
	{
		$queryArr = $obj->getQueryArr();
		$sql = 'delete from `'.$queryArr['tableName'].'`';
		$where = self::resolveWhere($queryArr['tableName'],$queryArr['where']);
		if($where)
		{
			$sql .= ' WHERE '.$where;
		}
		return $sql;
	}
	public static function count(module $obj)
	{
		$sql = self::query($obj);
		return preg_replace('$SELECT(.+?)FROM$i','SELECT COUNT(*) AS count FROM ',$sql);
	}
	/**
	 * MYSQL查询分析
	 * @param module $obj
	 */
	public static function query (module $obj)
	{
		$queryArr = $obj->getQueryArr();
		$addTableName = '`' . $queryArr['tableName'] . '`.';
		$joinOn = $where = $where2 = '';
		$queryArr['queryField'] = self::resolveQueryFields($queryArr['tableName'], $queryArr['queryField']);
		if ($queryArr['join'])
		{
			$joinArray = self::resolveJoin($queryArr['tableName'], $queryArr['join']);
			$queryFiled = !$queryArr['queryField'] && ! $joinArray['queryField'] ? '*' : $queryArr['queryField'] .($joinArray['queryField'] ? ',' : '').implode(',', $joinArray['queryField']);
			$joinOn = implode(' ', $joinArray['join']);
			$where = $joinArray['where'] ? implode(' AND ', $joinArray['where']) : '';
		} else
		{
			$queryFiled = $queryArr['queryField'] ? $queryArr['queryField'] : '*';
		}
		$sql = 'SELECT ' . $queryFiled . ' FROM `' . $queryArr['tableName'] .'` ' . $joinOn;
		$where2 = self::resolveWhere($queryArr['tableName'], $queryArr['where']);
		$sql .= $where2 || $where ? ' WHERE ' : '';
		$sql .= $where2;
		if ($where2 && $where)
		{
			$sql .= ' AND ' . $where;
		} else
		{
			$sql .= $where;
		}
		//分析ORDER
		if ($queryArr['group'])
		{
			$sql .= ' GROUP BY ' . $addTableName . '`' . $queryArr['group'] . '`';
		}
		if ($queryArr['order'])
		{
			$sql .= ' ORDER BY ' . $addTableName . '`' . $queryArr['order'][0] .
			 '` ' . ($queryArr['order'][1] == 1 ? 'desc' : 'asc');
		}
		if ($queryArr['limit'])
		{
			$sql .= ' LIMIT ' . $queryArr['limit'][0] . ',' .
			 $queryArr['limit'][1];
		}
		return $sql;
	}

	private static function resolveJoin ($tableName, $joinArray)
	{
		$returnArray = array('queryField' => array(), 'join' => array(), 'where' => array());
		foreach ($joinArray as $joinKey => $joinValue)
		{
			$queryArr = $joinValue[0]->getQueryArr();
			if ($queryArr['queryField'])
			{
				$queryArr['queryField'] = self::resolveQueryFields(
				$queryArr['tableName'], $queryArr['queryField']);
				$queryArr['queryField'] ? $returnArray['queryField'][] = $queryArr['queryField'] : '';
			}
			$whereString = self::resolveWhere($queryArr['tableName'], 
			$queryArr['where']);
			if ($whereString)
			{
				$returnArray['where'][] = $whereString;
			}
			$returnArray['join'][] = $joinValue[4] . ' JOIN `' . $queryArr['tableName'] . '` ON `' . $tableName . '`.`' .$joinValue[1] . '`' . $joinValue[2] . '`' . $queryArr['tableName'] . '`.`' . $joinValue[3] . '` ';
		}
		return $returnArray;
	}

	private static function resolveQueryFields ($tableName, $fieldNames)
	{
		if (is_array($fieldNames) && $fieldNames)
		{
			$array = array();
			foreach ($fieldNames as $fKey => $fValue)
			{
				if(!is_numeric($fKey))
					$array[] =  self::resolveSpecialChar($fKey).' AS '.self::resolveSpecialChar($fValue);
				else
					$array[] =  self::resolveSpecialChar($fValue);
			}
			return implode(',', $array);;
		} else if ($fieldNames)
		{
			return self::resolveSpecialChar($fieldNames);
		}
		return '*';
	}
	
	private static function resolveSpecialChar($value)
	{
		$value = trim($value);
		if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') ||  false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) 
		{
		    //如果包含* 或者 使用了sql方法 则不作处理
		}else{
		    $value = '`'.$value.'`';
		}
		return $value;
	}
	private static function resolveWhere ($tableName, $where)
	{
		if ($where)
		{
			$tmpSqlArr = array();
			foreach ($where as $whereKey => $whereValue)
			{
				if($whereValue[2] == 'betweenAnd')
				{
					$tmpSqlArr[] = '`' . $tableName . '`.`' . $whereValue[0] . '` between \''.$whereValue[1][0].'\' and \''.$whereValue[1][1].'\' ';
				} else if($whereValue[2] == 'in' || $whereValue[2] == 'not in')
				{
					$tmpSqlArr[] = '`' . $tableName . '`.`' . $whereValue[0] . '` ' .self::$_whereCondition[$whereValue[2]] . ' (' . $whereValue[1] .') ';
				} else
				{
					$tmpSqlArr[] = '`' . $tableName . '`.`' . $whereValue[0] . '` ' .self::$_whereCondition[$whereValue[2]] . ' \'' . $whereValue[1] .'\' ';
				}
			}
			return implode(' and ', $tmpSqlArr);
		}
		return '';
	}

	private static $_whereCondition = array('equal' => '=', 'gt' => '>', 
	'gte' => '>=', 'lt' => '<', 'lte' => ' <=', 'ne' => '!=', 'in' => 'in', 
	'nin' => 'not in', 'like' => 'like');
}